<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品</title>
    <link rel="stylesheet" href="layui/css/layui.css">
    <script src="layui/layui.js"></script>
</head>
<body>
    <!--搜索商品form页面-->
    <div class="layui-inline">
        <div class="layui-input-inline">
            <input type="text" name="pname" id="aaa"
                   placeholder="请填写图书名"
                   class="layui-input">
        </div>
    </div>
    <button class="layui-btn layui-btn-sm" id="search" lay-filter="search-department">搜索</button><br/>
    <a class="layui-btn  layui-btn-xs " id="myCart">我的购物车</a>
    <!--商品展示表格-->
    <table id="myTable" lay-filter="tableFilter"></table>
    <!--toolbar工具栏-->
    <script type="text/html" id="bar1">
        <a class="layui-btn layui-btn-xs" id="addCart" lay-event="addCart">加入购物车</a>
    </script>
    <!--layui代码-->
    <script>
        layui.use(['table','form','layer'],function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.$;
            //渲染表格
            table.render({
                elem:'#myTable',
                url:'product/show',
                height: 312,
                page:true,
                limits:[3,4,5],
                limit:3,
                cols:[[
                    {field:'pid',title:'商品编号',width:80, sort: true},
                    {field:'pname',title:'商品名',width:80, sort: true},
                    {field:'price',title:'单价',width:80, sort: true},
                    {field:'stock',title:'库存',width:80, sort: true},
                    {field:'des',title:'商品描述',width:180, sort: true},
                    {title:'操作', toolbar: '#bar1'},
                ]]
            })
            //搜索  点击搜索按钮触发单击事件  然后重载表格
            $('#search').click(function () {
                table.reload('myTable',{
                    where:{
                        pname:$('#aaa').val()
                    }
                    ,page: {
                        curr: 1 //重新从第 1 页开始
                    }
                })
            })
            //我的购物车
            $('#myCart').click(function () {
                location.href='cart.html'
            })
            //添加购物车
            table.on('tool(tableFilter)', function(obj){
                var data = obj.data; //获得当前行数据
                if(obj.event=='addCart'){
                    $.ajax({
                        url:'cart/add',
                        data:'pid='+data.pid,
                        success:function (result) {
                            if(result.flag){
                                layer.msg('添加购物车成功')
                                location.href='cart.html';
                            }else{
                                layer.msg('添加购物车失败');
                            }
                        }
                    })
                }
            })
        })
    </script>
</body>
</html>